package org.git.movie.videojiexi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.git.movie.videojiexi.common.util.VideoHelper;
import org.git.movie.videojiexi.enums.VideoChannel;
import org.git.movie.videojiexi.model.VideoModel;
import org.git.movie.videojiexi.service.VideoService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("TencentQqServiceV2Impl")
public class TencentQqServiceV2Impl implements VideoService {
    private static Logger log = LoggerFactory.getLogger(TencentQqServiceV2Impl.class);
    /**
     * 如何获取视频地址：
     * 在视频上-->点击鼠标右键-->复制视频页面地址
     * @param url
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public VideoModel parseUrl(String url, String userAgent) throws Exception {

        String flag = "qb://video/feedsvideo/list";
        String flag2 = "https://v.html5.qq.com/node/h5videoPlayer";
        String queryString = null;
        if(url.contains(flag)){
            queryString = url.replaceFirst(flag,"");
            queryString = queryString.trim();
        }else  if(url.contains(flag2)){
            queryString = url.replaceFirst(flag2,"");
            queryString = queryString.trim();
        }
        if(queryString.startsWith("?")){
            queryString = queryString.replaceFirst("\\?","");
        }

        Map<String,String> map = VideoHelper.parse2Map(queryString);
        String vid = map.get("vid");

        String htmlUrl = "https://v.html5.qq.com/node/h5videoPlayer?vid="+vid;

        Document doc = null;
        try {
            doc = Jsoup.connect(htmlUrl).get();
        } catch (Exception e) {
            ///e.printStackTrace();
            System.out.println(e.getMessage()+":--------------->"+url);
        }
        if( doc == null ){
            return  null;
        }
        Elements elScripts = doc.getElementsByTag("script");
        String vcontent = null;
        for(Element scriptItem :elScripts){
            String content =  scriptItem.data().toString();
            if(content != null && content.indexOf(" window.pageData") >= 0){
                vcontent = content.trim();
                break;
            }
        }
        if(vcontent != null){
            vcontent = vcontent.replace("window.pageData = ","");
            if(vcontent.endsWith(";")){
                vcontent =vcontent.substring(0,vcontent.length() -1);
            }
        }
        JSONObject jsonObject = JSON.parseObject(vcontent);

        JSONObject videoItem = jsonObject.getJSONObject("videoItem");
        String title = videoItem.getString("title");
        String imageUrl = videoItem.getString("imageUrl");
        String sPlayUrl = videoItem.getString("sPlayUrl");
        sPlayUrl = URLDecoder.decode(sPlayUrl,"UTF-8");
        String cdnplayUrl = null;
        if(videoItem.containsKey("cdnPlayInfo")){
            JSONObject cdnPlayInfo = videoItem.getJSONObject("cdnPlayInfo");
            JSONObject playUrls = cdnPlayInfo.getJSONObject("playUrls");
            JSONArray value = playUrls.getJSONArray("value");
            if(value != null && value.size() >= 1){
                cdnplayUrl = value.getString(0);
                cdnplayUrl = URLDecoder.decode(cdnplayUrl,"UTF-8");
            }
        }



//
        VideoModel rep = new VideoModel();
//        rep.setCover(picUrl);
//        rep.setFileType(fileType);
        if(cdnplayUrl != null){
            rep.setPlayAddr(cdnplayUrl);
        }else {
            rep.setPlayAddr(sPlayUrl);
        }

        rep.setChannel(VideoChannel.TencentQqV2);
        rep.setName(title);
        rep.setCover(imageUrl);

        return rep;
    }

    private String getVids(String url){
        String[] arUrl = url.split(".html")[0].split("/");
        return arUrl[arUrl.length-1];
    }

    public static void main(String[] args) throws Exception {
//        VideoModel rep =   new TencentQqServiceV2Impl().parseUrl("https://v.html5.qq.com/node/h5videoPlayer?vid=5984091005311059307&ch=&preloadShell=1&useShell=1&newSharePage=1&extinfo=ch%3D001500&topicid=151&sch=001505&invokeBy=&sc_id=3ORstoD","");
//        log.info(JSON.toJSONString(rep));
        VideoModel rep2 =   new TencentQqServiceV2Impl().parseUrl("qb://video/feedsvideo/list?vid=5776928654394377579&sh_na_id=1007&videoUrl=http%3A%2F%2Fshortv%2Ecdp%2Eqq%2Ecom%2Fszg%5F34350939%5F50001%5Fb6d6240a6782426ba3d544e882422f06%2Ef633%2Emp4%3Fdis%5Fk%3D3de715e6ed053749a19730ca398218bd%26dis%5Ft%3D1580710069%26bid%3Dqb%26seqid%3D1580710069441752%26network%3D1&cdnkey=R4TOtE00mPxDl2Pg2jJ3_9sCGZmowium5AK-1y6ubPMAZOinSBeREdORB5-m2-V0qY36y7MVmOOweORJQqwDAJO-ZGjxRqKCky1&expiretime=1580731669&sourcevid=o3055bze9ox&isNeedSniff=1&imageUrl=http%3A%2F%2Fcdn%2Eread%2Ehtml5%2Eqq%2Ecom%2Fimage%3Fsrc%3Dvideo%5Fhot%26q%3D5%26h%3D424%26w%3D750%26r%3D0%26imageUrl%3Dhttp%253A%252F%252Fpuui%2Eqpic%2Ecn%252Fqqvideo%5Fori%252F0%252Fo3055bze9ox%5F1280%5F720%252F0&title=%E5%8F%98%E5%BD%A2%E9%87%91%E5%88%9A4%EF%BC%9A%E6%93%8E%E5%A4%A9%E6%9F%B1%E5%A4%A7%E6%88%98%E6%9C%BA%E6%A2%B0%E6%81%90%E9%BE%99%EF%BC%8C%E8%B6%85%E7%87%83%E8%A7%86%E8%A7%89%E5%89%AA%E8%BE%91&contenturl=http%3A%2F%2Fv%2Ehtml5%2Eqq%2Ecom%2F%23p%3DzxSplayer%26vid%3D5776928654394377579&ch=001500&preloadShell=1&useShell=1&newSharePage=1&extinfo=appid%3D%26ch%3D001500%26ctr_scenes_id%3D110001%26gId%3D100264%2523122654%2523127039%2523128407%2523127294%2523100398%2523126022%2523121257%2523100466%2523125871%2523100767%2523125083%2523125203%2523126028%2523101218%2523120615%2523128629%2523125802%2523120610%2523103398%2523100000%2523120609%2523103943%2523107140%2523106289%2523127043%2523127684%2523110939%2523108086%2523108909%2523128059%2523111258%2523100000%2523113066%2523116608%2523127381%2523113207%2523128062%2523122084%2523125069%2523126644%2523124664%2523100000%2523129452%2523124665%2523126423%2523100000%2523122131%2523122175%2523122174%2523100000%2523100000%2523100000%2523100000%2523100000%2523100000%2523100000%2523100000%2523100000%26iRefreshNum%3D1%26iRunTime%3D121%26iTagId%3D1511001%26inner_ch%3D1026%26log_version%3D1%26mediaid%3Dqeh_16600814%26new_subject%3D10101%26polid%3D%26queryid%3D1580710069210%26sence_ext%3D%26src%3D65%26sub_sim%3D0%26type%3D27%26vid%3D5776928654394377579&titlePos=1","");
        log.info(JSON.toJSONString(rep2));
    }
}
